package dormouse.fx.renderers;

import java.net.URL;
import java.util.Arrays;
import java.util.List;

import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.layout.FlowPane;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.VFS;
import org.apache.log4j.Logger;

import com.google.common.base.Predicate;

import dormouse.vfs.FileUtil;
import dormouse.vfs.event.FileSelectionEvent;
import dormouse.vfs.event.FileSelectionEventMixin;
import dormouse.vfs.event.IFileSelectionListener;
import dormouse.vfs.event.ILocationChangeEvent;
import dormouse.vfs.ui.renderers.IFileListRenderer;

/**
 * This component is responsible for rendering a list of files as images in
 * on a light table.
 */
public class LightTable extends FlowPane implements IFileListRenderer<Node>{
	
	private static final Logger log = Logger.getLogger(LightTable.class);
	
	private static final String NAME = "Light Table";
	
	private FileSelectionEventMixin eventMixin = new FileSelectionEventMixin();
	
	
	/**
	 * Constructor
	 */
	public LightTable(){
		URL url = getClass().getResource("/fxml/LightTable.fxml");
		FXMLLoader loader = new FXMLLoader(url);
		loader.getController();
	}
	

	@Override
	public void render(FileObject dir, Predicate<FileObject> predicate) {
		try {
			render(Arrays.asList(dir.getChildren()), predicate);
		} catch (FileSystemException e) {
			log.error(e.getMessage(), e);
		}		
	}

	@Override
	public void render(String dir, Predicate<FileObject> predicate) {
		try {
			FileObject dirObject = VFS.getManager().resolveFile(dir);
			if (dirObject.getType() == FileType.FOLDER){
				render(dirObject, predicate);
			}
		} catch (FileSystemException e) {
			log.error(e.getMessage(), e);
		}
		
	}
	
	@Override
	public void render(List<FileObject> fileList,
			Predicate<FileObject> predicate) {
		
		//TODO: implement LightTable.	
		
	}

	@Override
	public Node getComponent() {
		return this;
	}

	@Override
	public void notifyFileSelectionListeners(FileObject selectedFile) {
		eventMixin.notify(new FileSelectionEvent(selectedFile));
	}

	@Override
	public void addFileSelectionListener(IFileSelectionListener listener) {
		eventMixin.addFileSelectionListener(listener);
	}

	@Override
	public void removeFileSelectionListener(IFileSelectionListener listener) {
		eventMixin.removeFileSelectionListener(listener);
	}

	@Override
	public void removeAllFileSelectionListeners() {
		eventMixin.removeAll();		
	}


	@Override
	public String getName() {
		return NAME;
	}


	@Override
	public void locationChanged(ILocationChangeEvent event) {
		FileObject currDir = event.getCurrentLocation();
		try {
			List<FileObject> fileList = FileUtil.createFileList(currDir.getChildren());
			render(fileList, null);
		} catch (FileSystemException e) {
			log.error(e.getMessage(), e);
		}
	}



}
